import random
import sys
import time

import pyautogui
import win32gui
import yaml

import os

# 直接选择config文件
config_file = None

# 输入选择config文件
if config_file == None:
    config_file_list = os.listdir('./config')
    for i, j in enumerate(config_file_list):
        print(i, j)
    while (choice := eval(input("请输入选择的配置文件编号："))) not in range(len(config_file_list)):
        print("输入错误，", end='')
    else:
        config_file = config_file_list[choice]

print(f"配置文件 {'./config/' + config_file} 读取中...")
with open('./config/' + config_file, "r", encoding="utf-8") as f:
    yaml_file = yaml.safe_load(f)

count_dict = {}
ERROE_SLEEP_TIME = int(yaml_file["script"]["error_sleep"])
TIME_FORMAT = yaml_file['script']['time_format']

for conf in yaml_file["script"]["window"]["title"]:
    try:
        title_config=conf.split(" ")
        if len(title_config)==1:
            title,x_remove,y_remove=title_config[0],0,0
        else:
            title,x_remove,y_remove=title_config[0],int(title_config[1]),int(title_config[2])
        hwnd = win32gui.FindWindow(None, title)
        left, top, right, bottom = win32gui.GetWindowRect(hwnd)
        # win32con.HWND_TOPMOST为置顶操作
        win32gui.SetWindowPos(hwnd, 0, x_remove, y_remove, yaml_file["script"]["window"]["width"],
                              yaml_file["script"]["window"]["height"], 0)
        print("窗口大小调节成功！")
    except Exception as e:
        print(f'窗口大小调节失败，原因可能是窗口未找到...{e}')

while (True):
    for workflows in yaml_file["script"]["workflows"]:
        try:
            for workflow in workflows:
                workflow = workflow.split(" ")
                if workflow[0] == "moveto_image":  # 识别图像并移动 图片名 置信度  x偏移量 y偏移量 移动时间
                    local = pyautogui.locateOnScreen(workflow[1],
                                                     confidence=float(workflow[2]))
                    x, y = pyautogui.center(local)
                    if len(workflow)==6:
                        pyautogui.moveTo(x + random.uniform(-1, 1) * float(workflow[3]),
                                         y + random.uniform(-1, 1) * float(workflow[4]),
                                         duration=random.random() * float(workflow[5]))
                    elif len(workflow)==8:
                        pyautogui.moveTo(x +float(workflow[3])+ random.uniform(-1, 1) * float(workflow[5]),
                                         y + float(workflow[4])+random.uniform(-1, 1) * float(workflow[6]),
                                         duration=random.random() * float(workflow[7]))
                elif workflow[0] == "if_image":  # 识别图像并移动 图片名 置信度  x偏移量 y偏移量 移动时间
                    local = pyautogui.locateOnScreen(workflow[1],confidence=float(workflow[2]))
                elif workflow[0] == "moveto_local":  # 移动至指定坐标 x y x偏移量 y偏移量 移动时间
                    pyautogui.moveTo(
                        float(workflow[1]) + random.uniform(-1, 1) * float(workflow[3]),
                        float(workflow[2]) + random.uniform(-1, 1) * float(workflow[4]),
                        duration=random.random() * float(workflow[5]))
                elif workflow[0] == "sleep":  # 睡眠 时间(秒) 随机值
                    time.sleep(float(workflow[1]) + random.random() * float(workflow[2]))
                elif workflow[0] == "click":  # 点击
                    pyautogui.click()
                elif workflow[0] == 'scroll':
                    pyautogui.scroll(clicks=int(workflow[1]))
                elif workflow[0] == "exit_count":  # 退出记次
                    if number_count := count_dict.get(workflow[1]):
                        count_dict[workflow[1]] += 1
                    else:
                        count_dict[workflow[1]] = number_count = 1
                    print(f"任务:{workflow[1]} 执行次数:{count_dict[workflow[1]]} {int(workflow[2])-count_dict[workflow[1]]}次后退出")
                    if count_dict[workflow[1]] >= int(workflow[2]):
                        sys.exit(0)
                elif workflow[0]=='count':
                    if number_count := count_dict.get(workflow[1]):
                        count_dict[workflow[1]] += 1
                    else:
                        count_dict[workflow[1]] = number_count = 1
                    print(f"任务:{workflow[1]} 计数:{count_dict[workflow[1]]}")
                elif workflow[0] == "exit":  # 退出
                    sys.exit(0)
                elif workflow[0] == "print":
                    print(f"{time.strftime(TIME_FORMAT)}{workflow[1]}")
                elif workflow[0]=='probabilistic_continue':
                    if (confirm:=float(workflow[1])-random.random())<0:
                        break
                else:
                    print(workflow)
                    print("配置有误")
        except TypeError as e:
            time.sleep(ERROE_SLEEP_TIME)
        except pyautogui.ImageNotFoundException as e:
            time.sleep(ERROE_SLEEP_TIME)
        except Exception as e:
            print(e)
            time.sleep(ERROE_SLEEP_TIME)
